<template>
  <div class="billing-detail">
    <h3>明细</h3>
    <el-form ref="formRef" :rules="rules" :model="formModel" label-width="160">
      <el-row>
        <el-form-item
          label="车辆类型"
          prop="vehicleType"
          v-if="props.data.diffVehicleType == 1"
        >
          <el-radio-group v-model="formModel.vehicleType">
            <el-radio
              v-for="item in vehicleTypeOptions"
              :key="item.id"
              :value="item.id"
              :label="item.id"
              >{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="车辆类型"
          prop="vehicleType"
          v-if="props.data.diffVehicleType == 0"
        >
          <el-radio-group v-model="formModel.vehicleType">
            <el-radio
              v-for="item in vehicleTypeOptions2"
              :key="item.id"
              :value="item.id"
              :label="item.id"
              >{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="免费时长(分钟)" prop="freeTime">
          <el-input-number
            v-model="formModel.freeTime"
            style="width: 260px"
            placeholder="请输入免费时长"
            :controls="false"
          />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="封顶类型" prop="maxType" v-if="props.data.periodType == 1">
          <el-radio-group v-model="formModel.maxType" @change="onChangemaxType">
            <el-radio
              v-for="item in maxTypeOptions"
              :key="item.id"
              :value="item.id"
              :disabled="item.disabled"
              :label="item.id"
              >{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="封顶类型"
          prop="maxType"
          @change="onChangemaxType"
          v-if="props.data.periodType == 2"
        >
          <el-radio-group v-model="formModel.maxType">
            <el-radio
              v-for="item in maxTypeBackupOptions"
              :key="item.id"
              :value="item.id"
              :disabled="item.disabled"
              :label="item.id"
              >{{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <div>
          <el-form-item label="封顶金额(元)" prop="max">
            <el-input-number
              v-model="formModel.max"
              style="width: 260px"
              placeholder="请输入封顶金额"
              :disabled="formModel.maxType === 0"
              :controls="false"
            />
          </el-form-item>
          <!-- <el-form-item label="具体封顶(元)" prop="max" v-else>
            <el-input-number
              v-model="formModel.max"
              style="width: 260px"
              placeholder="请输入具体封顶"
              :controls="false"
            />
          </el-form-item> -->
        </div>
      </el-row>
      <el-table
        :data="ruleItemList"
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
        @row-click="rowClickAdd"
      >
        <el-table-column label="序号" width="60" fixed="left">
          <template #default="scope">
            {{ (scope.$index + 1).toString() }}
          </template>
        </el-table-column>
        <el-table-column label="日期类型" min-width="90">
          <template #default="scope">
            <el-select
              v-if="props.data.periodType == 1"
              v-model="scope.row.dateType"
              filterable
              style="width: 160px"
            >
              <el-option
                v-for="item in dateTypeBackupOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select
              v-if="props.data.periodType == 2"
              v-model="scope.row.dateType"
              filterable
              style="width: 160px"
            >
              <el-option
                v-for="item in dateTypeBackupOptions2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="收费时段" min-width="150">
          <template #default="scope">
            <!-- <el-time-picker
              v-model="scope.row.timeRange"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="onChangeTimeRange"
              :format="'HH:mm:ss'"
            /> -->
            <div style="width: 100%; display: flex; justify-content: space-between">
              <el-time-select
                v-model="scope.row.startTime"
                style="width: 180px"
                :max-time="scope.row.endTime"
                class="mr-4"
                placeholder="请选择开始时间"
                start="00:00"
                step="00:15"
                end="24:00"
              />
              <el-time-select
                v-model="scope.row.endTime"
                style="width: 180px"
                :min-time="scope.row.startTime"
                placeholder="请选择结束时间"
                start="00:00"
                step="00:15"
                end="24:00"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="收费方式" width="140">
          <template #default="scope">
            <el-select v-model="scope.row.method" filterable>
              <el-option :value="1" :key="1" label="阶梯按时"></el-option>
              <el-option :value="2" :key="2" label="定额按次"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="具体规则">
          <template #default="scope">
            <el-button type="primary" @click="setRules(scope.row)">配置</el-button>
          </template>
        </el-table-column>
        <el-table-column label="时段封顶(元)">
          <template #default="scope">
            <el-input-number
              style="width: 100%"
              v-model="scope.row.periodMax"
              :controls="false"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="具体规则">
          <template #default="scope">
            <el-button :text="true" type="primary" @click="onAddLine">添加一行</el-button>
            <el-button
              v-if="ruleItemList.length > 1"
              :text="true"
              type="danger"
              @click="onDeleteLine(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="footer">
      <div class="search-btn">
        <el-button class="reset-btn" @click="resetRulesItem"> 取 消 </el-button>
        <el-button class="confirm-btn" @click="submitRulesIte">确 认 </el-button>
      </div>
    </div>
    <SequenceComponent
      ref="sequenceComponentRef"
      @operation-done="sequenceOperationDone"
    />
    <PunctualComponent
      ref="punctualComponentRef"
      @operation-done="punctualOperationDone"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import {
  cellStyle,
  headerCellStyle,
  maxTypeBackupOptions,
  maxTypeOptions,
  vehicleTypeOptions,
  vehicleTypeOptions2,
  dateTypeBackupOptions,
  dateTypeBackupOptions2,
  dateTypeOptions,
} from "../types";
import { ElMessage, dayjs } from "element-plus";
import SequenceComponent from "./sequenceComponent.vue";
import PunctualComponent from "./punctualComponent.vue";
import { generateUUID, formattingArrayOptions } from "../../../../../utils/common";

const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  editData: {
    type: Object,
    default: () => {},
  },
});
const formRef = ref("");
const sequenceComponentRef = ref("");
const punctualComponentRef = ref("");
const formModel = ref({});
const rules = reactive({
  maxType: [{ required: true, message: "请选择封顶类型" }],
  freeTime: [{ required: true, message: "请输入免费时长", trigger: "blur" }],
  vehicleType: [{ required: true, message: "请选择车辆类型" }],
  max: [
    {
      validator: (_rule, value, callback) => {
        if (formModel.value.maxType === 0) {
          callback();
        } else if (!value) {
          callback(new Error("请输入具体封顶"));
        } else {
          callback();
        }
      },
      trigger: "blur",
      required: true,
    },
  ],
});
const ruleItemList = ref([
  {
    uuid: generateUUID(),
  },
]);
const checkData = ref({});
const emits = defineEmits(["updateRule", "cancelRule"]);

const onAddLine = () => {
  ruleItemList.value.push({
    uuid: generateUUID(),
  });
};
const onChangemaxType = (val) => {
  if (val === 0) {
    delete formModel.value.max;
  }
};
const rowClickAdd = (row) => {
  checkData.value = row;
};
const setRules = (record) => {
  if (record.method) {
    if (record.method === 1) {
      punctualComponentRef.value?.init(record.itemRateList);
    } else {
      sequenceComponentRef.value?.init(record.fee);
    }
  } else {
    ElMessage.error("请先选择收费方式");
  }
};
const onDeleteLine = (index) => {
  ruleItemList.value.splice(index, 1);
};
const sequenceOperationDone = (data) => {
  checkData.value.itemRateList = [{ fee: data.fee }];
};
const punctualOperationDone = (data) => {
  checkData.value.itemRateList = data.list;
};
const resetRulesItem = () => {
  if (formRef.value) {
    formRef.value.clearValidate();
    formRef.value.resetFields();
    ruleItemList.value = [
      {
        uuid: generateUUID(),
      },
    ];
    formModel.value = {};
    checkData.value = {};
  }
  emits("cancelRule");
};
const formateRemark = (list) => {
  const result = [];
  list.forEach((el, index) => {
    console.log("index", index);
    const { startMinute, endMinute, fee, feeUnit } = el;
    if (index > 0) {
      result.push(`之后${endMinute - startMinute}分钟每${feeUnit}分钟${fee}元`);
    } else {
      result.push(`首${endMinute - startMinute}分钟每${feeUnit}分钟${fee}元`);
    }
  });
  return result.join(",");
};
const submitRulesIte = async () => {
  await formRef.value.validate();
  const result = ruleItemList.value.find((el) => {
    const {
      dateType,
      startTime,
      endTime,
      method,
      periodMax,
      itemRateList,
    } = ruleItemList.value[0];
    if (
      !dateType?.toString() ||
      !startTime ||
      !endTime ||
      !method?.toString() ||
      !periodMax?.toString() ||
      !itemRateList ||
      itemRateList.length === 0
    ) {
      return el;
    }
  });
  if (result) {
    ElMessage.error("计费规则明细配置不完整");
    return;
  }
  ruleItemList.value.forEach((data) => {
    data.vehicleType = formModel.value.vehicleType;
    data.maxType = formModel.value.maxType;
    data.max = formModel.value.maxType === 0 ? 0 : formModel.value.max;
    data.freeTime = formModel.value.freeTime;
    if (data.method === 2) {
      data.remark = `${formattingArrayOptions(dateTypeOptions, data.dateType)} ${
        data.itemRateList[0].fee
      }元/次`;
    } else {
      data.remark = `${formattingArrayOptions(dateTypeOptions, data.dateType)} ${
        data.startTime
      } - ${data.endTime} ${formateRemark(data.itemRateList)}`;
    }
    // delete data.uuid
  });
  emits("updateRule", ruleItemList.value);
};
const init = () => {
  if (props.editData.uuid) {
    formModel.value.vehicleType = props.editData.vehicleType;
    formModel.value.max = props.editData.max;
    formModel.value.maxType = props.editData.maxType;
    formModel.value.freeTime = props.editData.freeTime;
    ruleItemList.value = [
      {
        dateType: props.editData.dateType,
        startTime: props.editData.startTime,
        endTime: props.editData.endTime,
        method: props.editData.method,
        periodMax: props.editData.periodMax,
        itemRateList: props.editData.itemRateList,
        uuid: props.editData.uuid,
        remark: props.editData.remark,
      },
    ];
  }
};
init();
defineExpose({ resetRulesItem });
</script>

<style lang="less" scoped>
.table-container {
  margin-top: 16px;
  min-height: 100%;
  padding: 24px;
  background: #fff;
  border-radius: 6px;
}
.billing-detail {
  background: #f2f7fc;
  padding: 20px;
  margin-top: 24px;
}
.footer {
  width: 100%;
  display: flex;
  flex-direction: row-reverse;
  margin-top: 24px;
  .search-btn {
    display: flex;
    .reset-btn {
      width: 65px;
      height: 32px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #d9d9d9;
      font-weight: 400;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.65);
    }

    .confirm-btn {
      width: 65px;
      height: 32px;
      background: #007aff;
      border-radius: 2px;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
    }
  }
}
</style>
